<?php

namespace App\Console\Commands;

use App\Ant\Excel\Imports\ArchiveImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use App\Models\Company\Task as TaskModel;

class Task extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'task:archive {task_id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Task archive';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $task_id = $this->argument('task_id');
        TaskModel::where(function ($query) use ($task_id) {
            if ($task_id) {
                return $query->where('id', $task_id);
            }
        })->chunk(100, function (Collection $tasks) {
            $tasks->each(function (TaskModel $task) {
                if ($task->entry != $task->count) {
                    $task->sum_count = 0;
                    $task->save();
                    Excel::import(new ArchiveImport($task), 'public/' . $task->path);
                }
            });
        });
    }
}
